﻿using UnityEngine;
using UnityEngine.UI;

public class RedDot : MonoBehaviour
{
    public RedDotType redDotType;
    public object subType;
    public object parentSubType;

    /// <summary>
    /// 如果父级没有显示，那destroy不会触发，进行延迟注册
    /// </summary>
    private bool isNeedBind;

    private RedDotType tempRedDotType;
    private object tempSubType;
    private object tempParentSubType;
    private RedDotBindType tempBindType;

    private void OnEnable()
    {
        if (isNeedBind)
            BindRedDot(tempRedDotType, tempSubType, tempParentSubType, tempBindType);
    }

    /// <summary>
    /// 绑定红点数据（如果红点永远不会亮起，请不要绑定）
    /// </summary>
    /// <param name="redDotType">红点检测大类</param>
    /// <param name="subType">红点细化类型，如英雄ID等，没有细化类型可以不填</param>
    /// <param name="parentSubType">父类红点的subType</param>
    /// <param name="bindType">如果红点subType是一次性的，选择RedDotBindType.Once。</param>
    public void Bind(RedDotType redDotType, object subType = null, object parentSubType = null, RedDotBindType bindType = RedDotBindType.Const)
    {
        gameObject.SetActive(true);
        if (gameObject.activeInHierarchy)
        {
            BindRedDot(redDotType, subType, parentSubType, bindType);
        }
        else
        {
            tempBindType = bindType;
            tempRedDotType = redDotType;
            tempSubType = subType;
            tempParentSubType = parentSubType;
            isNeedBind = true;
        }
    }

    private void BindRedDot(RedDotType redDotType, object subType = null, object parentSubType = null, RedDotBindType bindType = RedDotBindType.Const)
    {
        isNeedBind = false;

        if (gameObject == null || redDotType == RedDotType.None)
            return;

        if (this.redDotType == redDotType && RedDotLayer.IsEquals(this.subType, subType) && RedDotLayer.IsEquals(this.parentSubType, parentSubType))
            return;


        ChangeRedState(false);

        RedDotMgr.Ins.BindRedDot(this, redDotType, subType, parentSubType, bindType);
    }

    public void ChangeRedState(bool isRed)
    {
        var image = gameObject.GetComponent<Image>();
        image.enabled = isRed;
    }

    private void OnDestroy()
    {
        RedDotMgr.Ins.UnbindRedDot(this);
    }
}
